import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {AlertComponent, DynamicComponent, DynamicComponentEvent} from '../../../../../ng-tools';
import {TicketService} from '../../../../services/api/ticket.service';
import {HttpParams} from '@angular/common/http';
import {Router} from '@angular/router';

@Component({
  selector: 'robot-group-item-add',
  templateUrl: './robot-group-item-add.component.html',
  styleUrls: ['./robot-group-item-add.component.scss']
})
export class RobotGroupItemAddComponent implements OnInit, DynamicComponent {
  context: any;
  groupID;
  dynamic: true;
  events: DynamicComponentEvent;
  allRobots = [];
  allRobotPage = 1;
  groupPage = 1;
  groupTotalPage;
  robotToatalPage;
  addRobot = [];
  choosedRobot = [];
  choosedRobotMuber = 0;
  isCompleted = false;
  alterOption = {
    theme: 'success',
    data: '',
    position: 'center'
  };
  @ViewChild('alert') private alert: AlertComponent;
  @Output() success = new EventEmitter();
  set data(value: any) {
    this.groupID = value;
  }
  constructor(private ticketService: TicketService,
              private router: Router) { }

  ngOnInit() {
    this.getRobotByGroup(1);
    this.getAllRobot(1);
  }
  change(e, data) {
    if (e.target.checked && this.addRobot.indexOf(data.userUid) === -1) {
        this.addRobot.push(data.userUid);
    } else if (!e.target.checked && this.addRobot.indexOf(data.userUid) !== -1) {
      this.addRobot.slice(this.addRobot.indexOf(data.userUid), 1);
    }
  }
  getAllRobot(page) {
      this.ticketService.get(this.ticketService.urls.getAllRobots, {
        observe: 'response',
        params: new HttpParams()
            .append('web_token', localStorage.getItem('token'))
            .append('pageNum', page + '')
            .append('notInRobotGroupId', this.groupID)
            .append('pageSize', '10')}).subscribe((resp) => {
        if (resp.body.success) {
          this.allRobots = resp.body.returnValue.page.list;
          this.robotToatalPage = resp.body.returnValue.page.pages;
          this.isCompleted = true;
        } else {
          this.router.navigateByUrl('/login').catch();
        }
      });
  }

  getRobotByGroup(page) {
    this.ticketService.get(this.ticketService.urls.getRobotsByGroupId, {
      observe: 'response',
      params: new HttpParams()
          .append('web_token', localStorage.getItem('token'))
          .append('pageNum', page + '')
          .append('robotGroupId', this.groupID)
          .append('pageSize', '10')}).subscribe((resp) => {
      if (resp.body.success) {
        this.choosedRobot = resp.body.returnValue.page.list;
        // this.getChooseRobotCompleted = true;
        this.choosedRobotMuber = this.choosedRobot.length;
        this.groupTotalPage = resp.body.returnValue.page.pages;
      } else {
        this.router.navigateByUrl('/login').catch();
      }
    });
  }
  chooseAll() {
    this.allRobots.forEach((item) => {
      if (this.addRobot.indexOf(item.userUid) === -1) {
        this.addRobot.push(item.userUid);
      }
    });
  }
  previousPage() {
    if (this.allRobotPage > 1) {
      this.allRobotPage = this.allRobotPage - 1;
    } else {
      this.allRobotPage = 1;
    }
    this.getAllRobot(this.allRobotPage);
  }
  nextPage() {
    if (this.allRobotPage < this.robotToatalPage) {
      this.allRobotPage = this.allRobotPage + 1;
    } else {
      this.allRobotPage = this.robotToatalPage;
    }
    this.getAllRobot(this.allRobotPage);
  }
  previousGroupPage() {
    if (this.groupPage > 1) {
      this.groupPage = this.groupPage - 1;
    } else {
      this.groupPage = 1;
    }
    this.getRobotByGroup(this.groupPage);
  }
  nextGroupPage() {
    if (this.groupPage < this.groupTotalPage) {
      this.groupPage = this.groupPage + 1;
    } else {
      this.groupPage = this.groupTotalPage;
    }
    this.getRobotByGroup(this.groupPage);
  }
  trigger(eventName: string, ...args) {
    this[eventName].emit(...args);
    if (eventName in this.events) {
      this.events[eventName](...args);
    }
  }
  addToGreoup() {
    if ((this.addRobot.length + this.choosedRobotMuber) < 15) {
        this.alterOption.data = '机器人总数必须大于等于15个';
        this.alterOption.theme = 'danger';
        this.alert.show(this.alterOption, 2000);
        return;
    }
    let addUserIds = '';
    for (const item of this.addRobot) {
      addUserIds += item + ',';
    }
    this.ticketService.post(this.ticketService.urls.addRobotToRobotGroup, {id: this.groupID, userIds: addUserIds.substring(0, addUserIds.length - 1)}, {
      observe: 'response',
      params: new HttpParams().append('web_token', localStorage.getItem('token'))}).subscribe((resp) => {
        if (resp.body.success) {
          this.trigger('success');
        }
    });
  }
}
